'''
Created on Oct 15, 2009

@author: Owner
'''
import os.path
import re
import gamemodel.state

class ResourceManager(object):
	'''
	classdocs
	'''
	DEFAULT_MANUAL_PATH = 'checker_manual'
	__MANUAL_BASE_DIR = None
	
	LINE_PATTERN = [re.compile('^(-([abAB-])){5}$'),
				re.compile('^(([abAB-])-){5}$'), \
				re.compile('^#{10}$')]
	LINE_SUB_PATTERN = [re.compile('-([abAB-])'),
				re.compile('^([abAB-])-')]
	
	ERROR = {'MANUAL_FORMAT': lambda f: \
				TypeError("Incorrect Manual File Format: ""{0}""".format(f))}
	
	def __init__(self):
		'''
		Constructor
		'''
	
	@staticmethod    
	def constructStateMap(fileName, player0 = None, player1 = None):
		ori_filename = fileName
		fileName = os.path.join(NS.getManualBastDir(), fileName)
		state = gamemodel.state.CheckerState.constructEmpty(player0, player1)
		
		#if no such file
		if not os.path.isfile(fileName):
			raise IOError('No such Checker Manual file!')
		
		fin = open(fileName)
		
		#first line
		line = fin.readline().strip()
		#if first line is not "############"
		if not NS.LINE_PATTERN[2].match(line):
			raise NS.ERROR['MANUAL_FORMAT'](ori_filename)
		
		ptn = 0
		for j in range(0, 10):
			line = fin.readline().strip()
			# if that line is not like '-P-P-P-P-P' or 'P-P-P-P-P-'
			# P could be a,b,A,B,-
			if not NS.LINE_PATTERN[ptn].match(line):
				raise NS.ERROR['MANUAL_FORMAT'](ori_filename)
			
			sub_pattern = NS.LINE_SUB_PATTERN[ptn]
			
			ptn = 1 - ptn
			NS.__importLineToState(state, line, sub_pattern, j, ptn)
		
		line = fin.readline().strip()	
		#if last line is not "############"
		if not NS.LINE_PATTERN[2].match(line):
			raise NS.ERROR['MANUAL_FORMAT'](ori_filename)
		
		return state
	
	@staticmethod
	def getManualBastDir():
		if NS.__MANUAL_BASE_DIR == None:
			dir = os.path.dirname(__file__)
			NS.__MANUAL_BASE_DIR = os.path.join(dir , NS.DEFAULT_MANUAL_PATH)
			
		return NS.__MANUAL_BASE_DIR
	
	@staticmethod
	def __importLineToState(state, line, pattern, line_number, x_shift):
		'''
		x_shift: 0 or 1, the x coordinate for the first possible piece of line
				1: if line_pattern is like '-P-P-P-P-P'
				0: if line_pattern is like 'P-P-P-P-P-'
		'''
		board = state.getBoard()
		i = 0
		while i < 10:
			s = line[i:i + 2]
			i+=2
			m = re.match(pattern, s)
			piece = m.group(1)
			bKing = piece == 'A' or piece == 'B'
			if piece == 'a' or piece == 'A':
				x = x_shift
				y = 9 - line_number
				player = state.getPlayers()[0]
			elif piece == 'b' or piece == 'B':
				x = 9 - x_shift
				y = line_number
				player = state.getPlayers()[1]
			else:
				x_shift+=2
				continue
			
			board.addPiece(player, x, y, bKing)	
			x_shift+=2
		
		pass
	
NS = ResourceManager